<template>
  <div class="top">
    <el-switch
      v-model="isDark"
      inline-prompt
      active-icon="Moon"
      inactive-icon="Sunny"
      @change="toggleTheme"
    />
    <lang-select class="ml-2 cursor-pointer" />
  </div>
  <div class="box">
    <el-card style="max-width: 480px">
      <h2>vue3-element-admin</h2>
      <!-- <span>{{ $t("login.title") }}</span> -->
      <el-form
        ref="loginFormRef"
        :model="loginData"
        :rules="loginRules"
        class="login-form"
      >
        <el-form-item prop="username">
          <div class="flex-y-center w-full">
            <svg-icon icon-class="user" class="mx-2" />
            <el-input
              ref="username"
              name="username"
              size="large"
              class="h-[48px]"
              v-model="loginData.username"
              :placeholder="$t('login.username')"
            />
          </div>
        </el-form-item>

        <!-- 密码 -->
        <el-tooltip placement="right" :content="$t('login.capsLock')">
          <el-form-item prop="password">
            <div class="flex-y-center w-full">
              <svg-icon icon-class="lock" class="mx-2" />
              <el-input
                type="password"
                name="password"
                size="large"
                class="h-[48px] pr-2"
                show-password
                v-model="loginData.password"
                @keyup="checkCapslock"
                @keyup.enter="handleLogin"
                :placeholder="$t('login.password')"
              />
            </div>
          </el-form-item>
        </el-tooltip>
        <!-- 验证码 -->
        <el-form-item prop="captchaCode">
          <div class="flex-y-center w-full">
            <svg-icon icon-class="captcha" class="mx-2" />
            <el-input
              auto-complete="off"
              size="large"
              class="flex-1"
              v-model="loginData.captchaCode"
              :placeholder="$t('login.captchaCode')"
            />

            <el-image
              class="rounded-tr-md rounded-br-md cursor-pointer h-[48px]"
              @click="getCaptcha"
              :src="captchaBase64"
            />
          </div>
        </el-form-item>
        <el-button
          @click.prevent="handleLogin"
          type="primary"
          style="width: 340px; height: 40px"
          >{{ $t("login.login") }}</el-button
        >
      </el-form>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { useSettingsStore, useUserStore } from "@/store";
import AuthAPI from "@/api/auth";
import { LoginData } from "@/api/auth/types";
import type { FormInstance } from "element-plus";
import {
  LocationQuery,
  LocationQueryValue,
  useRoute,
  useRouter,
} from "vue-router";
import router from "@/router";
import { ThemeEnum } from "@/enums/ThemeEnum";
const loginFormRef = ref<FormInstance>(); // 登录表单ref
const { t } = useI18n();
const loginRules = computed(() => {
  return {
    username: [
      {
        required: true,
        trigger: "blur",
        message: t("login.message.username.required"),
      },
    ],
    password: [
      {
        required: true,
        trigger: "blur",
        message: t("login.message.password.required"),
      },
      {
        min: 6,
        message: t("login.message.password.min"),
        trigger: "blur",
      },
    ],
    captchaCode: [
      {
        required: true,
        trigger: "blur",
        message: t("login.message.captchaCode.required"),
      },
    ],
  };
});

const captchaBase64 = ref(); // 验证码图片Base64
//验证码图片
const getCaptcha = () => {
  AuthAPI.getCaptcha().then((res) => {
    captchaBase64.value = res.captchaBase64;
    loginData.value.captchaKey = res.captchaKey;
  });
};

// 点击重新获取验证码
const loading = ref(false); // 按钮loading
const loginData = ref<LoginData>({
  username: "admin",
  password: "123456",
});

// 点击登录
const route = useRoute();
console.log(route.query)
function handleLogin() {
  loginFormRef.value?.validate((valid: boolean) => {
    if (valid) {
      loading.value = true;
      userStore
        .login(loginData.value)
        .then(() => {
          const query: LocationQuery = route.query;
          console.log(query);
          const redirect = (query.redirect as LocationQueryValue) ?? "/";
          const otherQueryParams = Object.keys(query).reduce(
            (acc: any, cur: string) => {
              if (cur !== "redirect") {
                acc[cur] = query[cur];
              }
              return acc;
            },
            {}
          );

          router.push({ path: redirect, query: otherQueryParams });
        })
        .catch(() => {
          getCaptcha();
        })
        .finally(() => {
          loading.value = false;
        });
    }
  });
}

// 黑暗模式

const userStore = useUserStore();
const settingsStore = useSettingsStore();
const isDark = ref(settingsStore.theme === ThemeEnum.DARK);
const icpVisible = ref(true);
const isCapslock = ref(false);
/** 检查输入大小写 */
function checkCapslock(event: KeyboardEvent) {
  // 防止浏览器密码自动填充时报错
  if (event instanceof KeyboardEvent) {
    isCapslock.value = event.getModifierState("CapsLock");
  }
}
const toggleTheme = () => {
  const newTheme =
    settingsStore.theme === ThemeEnum.DARK ? ThemeEnum.LIGHT : ThemeEnum.DARK;
  settingsStore.changeTheme(newTheme);
};

onMounted(() => {
  getCaptcha();
});
</script>
<style scoped lang="scss">
.top {
  height: 50px;
  display: flex;
  justify-content: right;
  .el-switch {
    margin: 10px;
  }
}
.box {
  width: 100vw;
  height: calc(100vh - 50px);
  background-size: cover;
  display: flex;
  justify-content: center;
  align-items: center;
  flex-direction: column;
}
.el-card {
  width: 400px;
  height: 470px;
  border-radius: 20px;
}
h2 {
  text-align: center;
  height: 100px;
  line-height: 100px;
}

.el-form {
  margin: 0 auto;
}

.el-form-item {
  background: var(--el-input-bg-color);
  border: 1px solid var(--el-border-color);
  border-radius: 5px;
}

:deep(.el-input) {
  .el-input__wrapper {
    padding: 0;
    background-color: transparent;
    box-shadow: none;

    &.is-focus,
    &:hover {
      box-shadow: none !important;
    }

    input:-webkit-autofill {
      /* 通过延时渲染背景色变相去除背景颜色 */
      transition: background-color 1000s ease-in-out 0s;
    }
  }
}
.flex-y-center {
  display: flex;
  align-items: center;
}
</style>